package com.platform.destiny.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.access.expression.SecurityExpressionHandler;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.expression.DefaultWebSecurityExpressionHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

/**
 * spring security 配置
 * <p>
 * PreAuthorize
 * PostAuthorize
 * PreFilter
 * PostFilter
 */
@Slf4j
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private AppSuccessHandler successHandler;
    @Autowired
    private AppFailureHandler failureHandler;
    @Autowired
    private AppDeniedHandler deniedHandler;
    @Autowired
    private AuthService authService;
    @Autowired
    private JwtTokenFilter authFilter;
    @Autowired
    private AppLogoutHandler logoutHandler;
    @Autowired
    private AppPermissionEvaluator permissionEvaluator;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        // userDetailService passwordEncoder
        auth.userDetailsService(authService)
                .passwordEncoder(passwordEncoder());
    }

    @Override
    @Bean(value = "authenticationManager")
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    /**
     * 去除 role_ 角色前缀
     *
     * @return
     */
    @Bean
    public SecurityExpressionHandler<FilterInvocation> webExpressionHandler() {
        DefaultWebSecurityExpressionHandler handler = new DefaultWebSecurityExpressionHandler();
        handler.setDefaultRolePrefix(""); // 去除 role_ 角色前缀
        handler.setPermissionEvaluator(permissionEvaluator);
        return handler;
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http.cors().disable();
        http.csrf().disable();
        http.headers().frameOptions().disable();
        // 以下两者均可
        // 添加 filter OncePerRequestFilter
        http.addFilterBefore(authFilter, UsernamePasswordAuthenticationFilter.class);
        // 添加 filter BasicAuthenticationFilter
        // http.addFilterBefore(new JwtAuthFilter(authenticationManagerBean()), UsernamePasswordAuthenticationFilter.class);
        // authorize 认证请求
        http.authorizeRequests()
                .expressionHandler(webExpressionHandler())
                .antMatchers("/login", "/login/user").permitAll()
                .anyRequest().authenticated();
        // 登录成功和失败处理器
        http.formLogin()
                .successHandler(successHandler)
                .failureHandler(failureHandler);

        // 禁用session , 使用 jwt
        http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
        // 访问越权处理器
        http.exceptionHandling().accessDeniedHandler(deniedHandler);
        // 退出登录
        http.logout().logoutUrl("/logout").logoutSuccessHandler(logoutHandler);


    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return NoOpPasswordEncoder.getInstance();
    }


    @Override
    public void configure(WebSecurity web) throws Exception {
        // super.configure(web);
        web.ignoring()
                .mvcMatchers("index");
    }


    /**
     * 跨域配置
     */
    @Bean
    public CorsFilter corsFilter() {
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(true);
        // 设置访问源地址
        // config.addAllowedOriginPattern("*");
        // 设置访问源请求头
        config.addAllowedHeader("*");
        // 设置访问源请求方法
        config.addAllowedMethod("*");
        // 有效期 1800秒
        config.setMaxAge(1800L);
        // 添加映射路径，拦截一切请求
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", config);
        // 返回新的CorsFilter
        return new CorsFilter(source);
    }

}
